package com.chencong.transform;

import com.chencong.env.FlinkTableEnv;
import com.chencong.udf.MyFlatMapFunc;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @Author chencong
 * @Description
 * @Date 7:28 下午 2021/8/9
 * @Param
 **/
public class Flink03UnboundedStreamingWordCount {
    public static void main(String[] args) throws Exception {
        // 1. 创建流式执行环境
        StreamExecutionEnvironment streamTableEnvironment = FlinkTableEnv.getStreamTableEnvironment();
        //设置并行度
        streamTableEnvironment.setParallelism(1);

        //2 读取端口数据
        DataStreamSource<String> socketData = streamTableEnvironment.socketTextStream("localhost", 9999);

        //3 逻辑
        SingleOutputStreamOperator<String> flatMapData = socketData.flatMap(new MyFlatMapFunc());

        SingleOutputStreamOperator<Tuple2<String, Integer>> oneToTupleData = flatMapData.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String s) throws Exception {
                return Tuple2.of(s, 1);
            }
        });

        KeyedStream<Tuple2<String, Integer>, String> keyByData = oneToTupleData.keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
            @Override
            public String getKey(Tuple2<String, Integer> stringIntegerTuple2) throws Exception {
                return stringIntegerTuple2.f0;
            }
        });

        SingleOutputStreamOperator<Tuple2<String, Integer>> result = keyByData.sum(1);

        result.print();
        //4 执行 nc -lk 9999
        streamTableEnvironment.execute();



    }
}
